﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VideoCache.Server.MVCWeb.Areas.Member.Models;
using VideoCache.Server.BLL;
using System.Web.Security;
using VideoCache.Server.Model;
using Fsb.Utility;

namespace VideoCache.Server.MVCWeb.Areas.Member.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Member/Login/
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (UserBLL.ValidateUser(model.UserName, model.Password))
                    {
                        UserInfo info = UserBLL.GetUserByName(model.UserName);
                        string json = JsonUtility.Json(info);
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddDays(1), true, json);
                        string encryptTicket = FormsAuthentication.Encrypt(ticket);
                        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
                        Response.Cookies.Add(authCookie);

                        return string.IsNullOrEmpty(returnUrl) ? (ActionResult)RedirectToAction("Index", "Member") : (ActionResult)Redirect(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("Error", "账号或密码错误。");
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("Error", ex.Message);
                }
            }
            return View(model);
        }
    }
}